import request from '@/utils/request'
import { User, Profile, ProfileAction } from '../reducers/profile'
import { RootThunkAction } from '../index'
// 保存用户信息
export const saveUser = (payload: User): ProfileAction => {
  return {
    type: 'profile/user',
    payload: payload,
  }
}

/**
 * 获取用户基本信息
 */
export const getUser = (): RootThunkAction => {
  return async (dispatch) => {
    const res = await request.get('/user')
    // console.log(res)
    dispatch(saveUser(res.data))
  }
}

export const saveProfile = (payload: Profile): ProfileAction => {
  return {
    type: 'profile/profile',
    payload: payload,
  }
}

// 获取用户详情信息
export const getProfile = (): RootThunkAction => {
  return async (dispatch) => {
    const res = await request('/user/profile')
    dispatch(saveProfile(res.data))
  }
}

// 属性变成可选
type PartialPfofile = Partial<Profile>
// 修改用户个人信息
export const updateProfile = (data: PartialPfofile): RootThunkAction => {
  return async (dispatch) => {
    await request.patch('/user/profile', data)
    dispatch(getProfile())
  }
}

// 上传头像
export const updatePhoto = (fd: FormData): RootThunkAction => {
  return async (dispatch) => {
    await request.patch('/user/photo', fd)
    dispatch(getProfile())
  }
}
